package 第三周;

/*
 * @author  YxinMiracle
 * @date  2022-04-26 21:07
 * @Gitee: https://gitee.com/yxinmiracle
 */


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    @Override
    public String toString() {
        return "TreeNode{" +
                "val=" + val +
                ", left=" + left +
                ", right=" + right +
                '}';
    }
}


public class 验证二叉搜索树 {

    public boolean isValidBST(TreeNode root) {
        return check(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }

    public boolean check(TreeNode root, long leftRange, long rightRange) {
        if (root == null) return true;
        if (root.val < leftRange || root.val > rightRange) return false;
        return check(root.left, leftRange, (long) root.val - 1) && check(root.right, (long) root.val + 1, rightRange);
    }
}
